from exts import db
from werkzeug import generate_password_hash,check_password_hash
from datetime import datetime

'''
账号所有权对应关系：
用户----- 角色 ----所有权

'''

class CMSPermission():
    #账号权限
    #255 二进制的形式1111 1111 拥有所有权限
    ALL_PERMISSION = 0b11111111
    #1、访问者权限
    VISITOR =        0b00000001
    #2、管理帖子权限
    POSTER  =        0b00000010
    #3、管理评论权限
    COMMENTER =      0b00000100
    #4、管理板块权限
    BOAEDER =        0b00001000
    #5、管理前台用户权限
    FRONTUSER =      0b00010000
    #6、管理后台用户权限
    CMSUSER =        0b00100000

    #7、管理后台管理员的权限
    ADMINER =        0b01000000

cms_role_user = db.Table(
    "cms_role_user",
    db.Column("cms_role_id",db.Integer,db.ForeignKey("cms_roles.id"),primary_key=True),
    db.Column("cms_user_id",db.Integer,db.ForeignKey("cms_users.id"),primary_key=True)
)



class CMSRole(db.Model):
    #角色 数据库
    __tablename__ = "cms_roles"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50),nullable=False)
    desc = db.Column(db.String(100),nullable=True)
    creat_time = db.Column(db.DateTime,default=datetime.now)
    permissions = db.Column(db.Integer,default=CMSPermission.VISITOR)

    users = db.relationship("CMSUser",secondary=cms_role_user,backref="roles")

class CMSUser(db.Model):
    __tablename__ = "cms_users"
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(50),nullable=False)
    _password = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(50),nullable=False,unique=True)
    join_time = db.Column(db.DateTime, default=datetime.now)


    def __init__(self,username,password,email):
        self.username = username
        self.password = password
        self.email = email

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self,raw_password):
        self._password = generate_password_hash(raw_password)

    def check_password(self,raw_password):
        result = check_password_hash(self.password,raw_password)
        return  result

    #找到这个用户所有用的权限
    @property
    def permissions(self):
        if not self.roles:
            return 0

        all_permissions = 0
        # print(self.roles)
        for role in self.roles:
            # print(role)
            permissions = role.permissions
            # print(permissions)
            all_permissions |= permissions
        return  all_permissions

    def has_permission(self,permission):
        return self.permissions & permission == permission

    @property
    def is_developer(self):
        return self.has_permission(CMSPermission.ALL_PERMISSION)
